from django import forms
from app01 import models
from django.core.validators import RegexValidator  # 正则表达式


class RegisterModelFOrm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        """重写init给所有字段动态添加属性"""
        super(RegisterModelFOrm, self).__init__(*args, **kwargs)
        for name, field in self.fields.items():  # name对应的就是每个字段的名字,field对应的是对象
            field.widget.attrs['class'] = 'form-control'  # 添加class属性
            field.widget.attrs['placeholder'] = '请输入%s' % field.label  # 添加placeholder属性field.label拿到介绍

    phone = forms.CharField(label='我是手机号',
                            validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机格式错误')])  # 重写数据库字段 加入正则表达式
    password = forms.CharField(label='密码', widget=forms.PasswordInput())  # 将密码改写成为密文
    passwords = forms.CharField(label='重复密码', widget=forms.PasswordInput())  # 将密码改写成为密文attrs用来给生成的标签添加属性
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'passwords', 'phone', 'code']
